<?php defined('SYSPATH') OR die('No direct access allowed.');
class User_Model extends ORM
{
	protected $has_and_belongs_to_many = array('codes');
	/**
	 * 验证用户使用OpenID登陆
	 *
	 * @param string			从OpenID服务商处获取的令牌
	 * @return array|boolean	
	 */
	public function auth($token)
	{
		$apiKey = Kohana::config('core.rpxKey');
		$postData = array(
			'token'		=>	$token,
			'apiKey'	=>	$apiKey,
			'format'	=>	'json'
		);
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_URL, 'https://rpxnow.com/api/v2/auth_info');
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		$rawJson = curl_exec($curl);
		curl_close($curl);

		// parse the json response into an associative array
		$authInfo = json_decode($rawJson, true);
		if($authInfo['stat'] == 'ok')
		{
			return $authInfo['profile'];
		}
		else
		{
			return false;
		}
	}

	/**
	 * 添加用户
	 *
	 * @param array 	OpenID的用户信息
	 * @return boolean
	 */
	public function addUser($authInfo)
	{
		$this->identifier = $authInfo['identifier'];
		$this->username = $authInfo['displayName'];
		$this->regdate = time();
		$this->apikey = md5(mt_rand().uniqid());
		isset($authInfo['email'])?$this->email = $authInfo['email']:'';
		user::set_login_cookie($this->apikey);
		$this->save();
		return $this->id;
	}

	/**
	 * 保存设置
	 * @param array 设置信息
	 */ 
	public function saveSetting($info)
	{
		$row = $this->db->update($this->table_name,$info,array('id'=>Session::instance()->get('userId')));
		return $row;
	}

}
